
function ToolBox() {
	this.type = 'pencil';
	this.strokeColor = '#000000';
	this.fillColor = 'rgba(0,0,0,0)';
	this.lineWidth = 1;
	this.textAlign = 'left';
	this.fontFamily = 'Arial';
	this.fontSize = '20px';
	this.fontWeight = 'bold';
	this.fontStyle = 'normal';
	this.zoom = 1.0;
	this.size = [];
};
function InitCanvas(cav) {
    var ctx = cav.getContext("2d");
	ctx.fillStyle = "#000000";
    ctx.fillRect(0,0,cav.width,cav.height);
}
// scope: global
window.toolbox = new ToolBox();
$(function() {
    var cav = document.getElementById("canvas1");
    var ctx = cav.getContext("2d");
    InitCanvas(cav);
    /*使用 paper.js 的 API 和 事件响应机制，绘制各种图形*/
	paper.install(window);
	paper.setup('canvas1');
	//定义鼠标松开事件，将绘制的图形保留入栈
	function onMouseUp(e) {
	    if (window.toolbox.type != 'Zhexian' && window.toolbox.type != 'Bezier'){
	        path = null;
	    }

	}
	//pencil method
	var pencil = new Tool();
	var path = null;
	pencil.onMouseDown = function(e) {
	    path = new Path();
	    path.strokeColor = window.toolbox.strokeColor;
	    path.add(e.point);
	    path.strokeWidth = window.toolbox.lineWidth;

	};
	pencil.onMouseDrag = function(e) {
	    path.add(e.point);
	    path.strokeWidth = window.toolbox.lineWidth;
	};
	pencil.onMouseUp = onMouseUp;
	/* 画椭圆*/
	var ellipse = new Tool();
	ellipse.onMouseDrag = function(e) {
	    path = new Path.Ellipse({
	        point: [e.downPoint.x,e.downPoint.y],
	        size: [(e.point.x-e.downPoint.x),(e.point.y-e.downPoint.y)],
	        strokeColor: window.toolbox.strokeColor,
	        fillColor: window.toolbox.fillColor
	    });
	    path.strokeWidth = window.toolbox.lineWidth;
	    path.removeOnDrag();
	};
	ellipse.onMouseUp = onMouseUp;
	// 画五角星
	var star = new Tool();
	star.onMouseDrag = function(e) {
	    var centers = e.downPoint;
	    var points = 5;
	    var r1 = e.point.x - e.downPoint.x;
	    var r2 = e.point.y - e.downPoint.y;
	    //var r = r1>r2?r1:r2;
	    var r = Math.sqrt(r1*r1+r2*r2);
	    var delta = new Point([e.point.x - e.downPoint.x, e.point.y - e.downPoint.y]);
	    path = new Path.Star({
	        center: centers,
	        points: 5,
	        radius1: r1,
	        radius2: r1*0.38,
	        strokeColor: window.toolbox.strokeColor,
	        fillColor: window.toolbox.fillColor,
	        strokeWidth: window.toolbox.lineWidth
	    });
	    path.rotate(delta.angle);   //使五角星可以根据鼠标旋转
	    path.removeOnDrag();
	};
	star.onMouseUp = onMouseUp;
	//矩形
	var rectangle = new Tool();
	rectangle.onMouseDrag = function(e) {
	    path = new Path.Rectangle(e.downPoint,e.point);
	    path.strokeColor = window.toolbox.strokeColor;
	    path.fillColor = window.toolbox.fillColor;
	    path.strokeWidth = window.toolbox.lineWidth;
	    path.removeOnDrag();
	}
	rectangle.onMouseUp = onMouseUp;
	//直线
	var line = new Tool();
	line.onMouseDrag = function(e) {
	    path = new Path.Line(e.downPoint,e.point);
	    path.strokeColor = window.toolbox.strokeColor;
	    path.fillColor = window.toolbox.fillColor;
	    path.strokeWidth = window.toolbox.lineWidth;
	    path.removeOnDrag();
	}
	line.onMouseUp = onMouseUp;
	//画刷，还没有实现的算法
	var brush = new Tool();
	var minSize = 5;
	brush.maxDistance = 20;
	brush.onMouseDrag = function(event) {
	    if (event.delta.length > minSize) {

		}
	}
	brush.onMouseUp = function(event){
		if (path) {
			path.add(event.point);
			path.closed = true;
			path.smooth();
			path = null;
		}
	}
	
	//波浪形线
	var clouds = new Tool();
	clouds.onMouseDown = function(e) {
	    path = new Path();
	    path.strokeColor = window.toolbox.strokeColor;
	    path.strokeWidth = 5;
	    path.strokeCap = "round";
	    path.strokeJoin = "round";
	    path.add(e.point);
	}
	clouds.onMouseDrag = function(e) {
	    path.arcTo(e.point,true);
	}
	clouds.onMouseUp = onMouseUp;
	//绘制正三角形，可以旋转
	var triangle = new Tool();
	triangle.onMouseDrag = function(e) {
	    var center = e.downPoint;
	    var slides = 3;
	    var radius = Math.sqrt(Math.pow((e.downPoint.x-e.point.x),2)+Math.pow((e.downPoint.y-e.point.y),2));
	    path = new Path.RegularPolygon(center,slides,radius);
	    path.fillColor = window.toolbox.fillColor;
	    path.strokeColor = window.toolbox.strokeColor;
	    path.strokeWidth = window.toolbox.lineWidth;
	    var delta = new Point([e.point.x - e.downPoint.x, e.point.y - e.downPoint.y]);
	    path.rotate(delta.angle);
	    path.removeOnDrag();
	}
	triangle.onMouseUp = onMouseUp;
	//六边形
	var polygon = new Tool();
	polygon.onMouseDrag = function(e) {
	    var center = e.downPoint;
	    var slides = 6;
	    var radius = Math.sqrt(Math.pow((e.downPoint.x-e.point.x),2)+Math.pow((e.downPoint.y-e.point.y),2));
	    path = new Path.RegularPolygon(center,slides,radius);
	    path.fillColor = window.toolbox.fillColor;
	    path.strokeColor = window.toolbox.strokeColor;
	    path.strokeWidth = window.toolbox.lineWidth;
	    var delta = new Point([e.point.x - e.downPoint.x, e.point.y - e.downPoint.y]);
	    path.rotate(delta.angle);
	    path.removeOnDrag();
	}
	polygon.onMouseUp = onMouseUp;
	//bezier曲线
	var handleIn = new Point(0,0);
	var handleOut = new Point(0,0);
	/* Sample
	var firstPoint = new Point(100, 50);
	var firstSegment = new Segment(firstPoint, null, handleOut);

	var secondPoint = new Point(300, 50);
	var secondSegment = new Segment(secondPoint, handleIn, null);

	var path = new Path(firstSegment, secondSegment);
	path.strokeColor = 'black';
	*/
	var bezier = new Tool();
	var points = new Array();
	bezier.onMouseDown = function(e){
		if (points.length == 0){
			points.push(e.point);
		}
	}
    bezier.onMouseDrag = function(e){
		if (points.length == 1){
			var tmpSeg1 = new Segment(points[0],null,handleOut);
			var tmpSeg2 = new Segment(e.point,handleIn,null);
			path = new Path(tmpSeg1,tmpSeg2);
			path.strokeColor = window.toolbox.strokeColor;
			path.removeOnDrag();
		}
		if (points.length == 2){
			path.removeOnDrag();
			handleOut = new Point([e.point.x - e.downPoint.x, e.point.y- e.downPoint.y]);
			var tmpSeg1 = new Segment(points[0],null,handleOut);
			var tmpSeg2 = new Segment(points[1],handleIn,null);
			path = new Path(tmpSeg1,tmpSeg2);
			path.strokeColor = window.toolbox.strokeColor;
			path.removeOnDrag();
		}
		if (points.length == 3){
			path.removeOnDrag();
			handleOut = points[2];
			handleIn = new Point([e.point.x - e.downPoint.x, e.point.y- e.downPoint.y]);
			var tmpSeg1 = new Segment(points[0],null,handleOut);
			var tmpSeg2 = new Segment(points[1],handleIn,null);
			path = new Path(tmpSeg1,tmpSeg2);
			path.strokeColor = window.toolbox.strokeColor;
			path.removeOnDrag();
		}

    }
	bezier.onMouseUp = function(e) {
		if (points.length == 3){
			while (points.length != 0){
				points.pop();
			}
			handleIn = new Point(0,0);
			handleOut = new Point(0,0);
		}
		if (points.length == 2){
			points.push(new Point([e.point.x - e.downPoint.x, e.point.y- e.downPoint.y]));
		}
		if (points.length == 1){
			points.push(e.point);
		}

	}

	//自由线
    var zhexian = new Tool();
    zhexian.onMouseDown = function(e) {
        if (!path) {
            path = new Path();
            path.fillColor = window.toolbox.fillColor;
            path.strokeColor = window.toolbox.strokeColor;
            path.strokeWidth = window.toolbox.strokeWidth;
            path.add(e.point);
        } else {
            path.add(e.point);
        }
    }
    zhexian.onMouseUp = onMouseUp;
    //爆炸星形
    var baozha = new Tool();
    baozha.onMouseDown = function(e) {
    }
    baozha.onMouseDrag = function(e) {
        var delta = new Point([e.point.x - e.downPoint.x, e.point.y - e.downPoint.y]);
        var radius = delta.length;
        var points = 5 + Math.round(radius/50);
        path = new Path.Star({
            center: e.downPoint,
            fillColor: window.toolbox.fillColor,
            strokeColor: window.toolbox.strokeColor,
            strokeWidth: window.toolbox.strokeWidth,
            points: points,
            radius1: radius / 2,
            radius2: radius
        });
        path.rotate(delta.angle);
        path.removeOnDrag();
    }
    baozha.onMouseUp = onMouseUp;
    //圆角矩形
    var roundRect = new Tool();
    roundRect.onMouseDrag = function(e) {
        var rect = new Rectangle(e.downPoint,e.point);
        var cornerSize = new Size(20,20);
        path = new Path.RoundRectangle(rect, cornerSize);
        path.fillColor = window.toolbox.fillColor;
        path.strokeColor = window.toolbox.strokeColor;
        path.strokeWidth = window.toolbox.strokeWidth;
        path.removeOnDrag();
    }
    roundRect.onMouseUp = onMouseUp;
	//取色器
	var dropper = new Tool();
	dropper.onMouseDown = function(e){
		var color = ColorPicker("canvas1", e.point.x, e.point.y);
		//console.log(color);
		$("#firstColor").css("background-color",color);
		window.toolbox.strokeColor = color;
	}
	dropper.onMouseUp = onMouseUp;
	//橡皮擦
	var eraser = new Tool();
	eraser.onMouseDown = function(e) {
		path = new Path.Rectangle(new Point([e.point.x-5, e.point.y-5]),new Point(e.point.x+5, e.point.y+5));
		path.fillColor = "#ffffff";
		path.strokeColor = "#ffffff";
	}
	eraser.onMouseDrag = function(e){
		path = new Path.Rectangle(new Point([e.point.x-5, e.point.y-5]),new Point(e.point.x+5, e.point.y+5));
		path.fillColor = "#ffffff";
		path.strokeColor = "#ffffff";
	}
	eraser.onMouseUp = onMouseUp;
	var text = new Tool();
	text.onMouseDrag = function(e){
	}

	var select = new Tool();
	select.onMouseDrag = function(e) {

	}
	//剪切过程
	var cut = new Tool();

    /*
    //对话框，没有实现
    var duihuakuang = new Tool();
    duihuakuang.onMouseDrag = function(e) {
        //project = new Project();
        var svg = document.getElementById('duihuakuang');
        svg.style.display = 'block';
        var dhk = project.importSVG(svg);
        svg.style.display = 'none';
        dhk.position = e.downpoint;
        paper.view.draw();
        
    }*/
	/*When Button Click*/
	$("#eraserButton").click(function(){
		eraser.activate();
	});
	$("#pencilButton").click(function() {
	    pencil.activate();
	    
	});
	$("#Line").click(function() {
	    line.activate();
	});
	$("#Bezier").click(function() {
	    bezier.activate();
	});
	$("#Triangle").click(function() {
	    triangle.activate();
	});
	$("#Rectangle").click(function() {
	    rectangle.activate();
	});
	$("#Wujiaoxing").click(function() {
	    star.activate();
	});
	$("#Duobianxing").click(function() {
	    polygon.activate();
	});
	$("#Ellipse").click(function() {
	    ellipse.activate();
	});
	$("#Baozha").click(function() {
	    baozha.activate();
	});
	$("#Zhexian").click(function() {
	    zhexian.activate();
	});
	$("#RoundRect").click(function() {
	    roundRect.activate();
	});
	$("#brushButton").click(function(){
		brush.activate();
	});
	$("#dropperButton").click(function() {
		dropper.activate();
	});
	/*下面的代码用于控制界面UI的变化*/
	
	updateUI();
	$(window).resize(function(){
		updateUI();
	});
	$("#pencilButton").addClass("leftbarButtonSelect");
	$(".leftbarButton").each(function(index, element) {
        $(this).click(function() {
			var buttonId = $(this).attr("id");
			if (buttonId == "dropperButton") {
				lastTool = window.toolbox.type;
			}
			var pos = buttonId.indexOf('Button',0);
			var type = buttonId.substr(0,pos);
			console.log(type);
			
			window.toolbox.type = type;
			var buttons = $(".leftbarButton");
			var i;
			for (i=0;i<buttons.length;i++){
				if (buttons.eq(i).hasClass("leftbarButtonSelect")){
					buttons.eq(i).removeClass("leftbarButtonSelect");
				}
			}
			$(this).addClass("leftbarButtonSelect");
			switch(type) {
				case "eraser":	
				case "pencil":	$("#lineStyle").show();
										$("#fontStyleOption").hide();
										$("#zoomInOut").hide();
										break;
				case "text": 		$("#lineStyle").hide();
										$("#fontStyleOption").show();
										$("#zoomInOut").hide();
										$("#fontColor").css("background-color",$("#firstColor").css("background-color"));
										break;
				case "magnifier":	$("#lineStyle").hide();
										$("#fontStyleOption").hide();
										$("#zoomInOut").show();
										break;
				default: 				$("#lineStyle").hide();
										$("#fontStyleOption").hide();
										$("#zoomInOut").hide();
										break;
			}
		});
    });
	$(".frame").resizable();
	$(".frame").resize(function(e) {
		var width = $(this).width();
		var height = $(this).height();
		var url = cav.toDataURL();
		$("#canvas1").remove();
		$(this).append('<canvas id="canvas1" width="'+width+'" height="'+height+'">');
		$("#canvas1").width(width);
		$("#canvas1").height(height);
		paper.setup('canvas1');

	});
	$(".colorCell").each(function(index, element) {
        $(this).click(function() {
			var color = $(this).css("background-color");
			$("#firstColor").css("background-color",color);
			$("#fontColor").css("background-color",color);
			window.toolbox.strokeColor = color;
		});
    });
	$("#firstColor").click(function(){
		var color1 = $("#firstColor").css("background-color");
		var color2 = $("#secondColor").css("background-color");
		$("#firstColor").css("background-color",color2);
		$("#secondColor").css("background-color",color1);
		$("#fontColor").css("background-color",color2);
		window.toolbox.strokeColor = color2;
		if ($("#fillStyle").val() != 0) 
		    window.toolbox.fillColor = color1;
		else 
		    window.toolbox.fillColor = 'rgba(0,0,0,0)';
	});
	$("#secondColor").click(function() {
		var color1 = $("#firstColor").css("background-color");
		var color2 = $("#secondColor").css("background-color");
		$("#firstColor").css("background-color",color2);
		$("#secondColor").css("background-color",color1);
		$("#fontColor").css("background-color",color2);
		window.toolbox.strokeColor = color2;
		if ($("#fillStyle").val() != 0) 
		    window.toolbox.fillColor = color1;
		else 
		    window.toolbox.fillColor = 'rgba(0,0,0,0)';
		
	});
	$(".shapeButtonBox").each(function(index, element) {
        $(this).click(function() {
			var name = $(this).attr("id");
			$("#lineStyle").show();
			$("#fontStyleOption").hide();
			$("#zoomInOut").hide();
			window.toolbox.type = name;
			console.log(window.toolbox.type);
			var buttons = $(".leftbarButton");
			var i;
			for (i=0;i<buttons.length;i++){
				if (buttons.eq(i).hasClass("leftbarButtonSelect")){
					buttons.eq(i).removeClass("leftbarButtonSelect");
				}
			}
			$("#pencilButton").addClass("leftbarButtonSelect");
		});
    });
	$("#undoButton").click(function() {
	});
	$("#redoButton").click(function(){
	});
	$("#lineStyleOption").change(function() {
		var text = $(this).find("option:selected").text();
		var val = $(this).find("option:selected").val();
		window.toolbox.lineWidth = val;
		$(this).attr("data-line",val);
		console.log("Value",val);
	});
	$("#fontFamily").change(function() {
		var text = $(this).find("option:selected").text();
		var val = $(this).find("option:selected").val();
		$(this).data("fontfamily",val);
		myTool.setFontFamily(val);
	});
	$("#fontSize").change(function(){
		var val = $(this).find("option:selected").val();
		$(this).data("fontsize",val);
		myTool.setFontSize(val);
		$("#textField").css("font-size",val);
		console.log("Font Size Changed:",val);
	});
	$("#fillStyle").change(function() {
		var val = $(this).find("option:selected").val();
		console.log(val);
		//myTool.setFillStyle($("#firstColor").css("background-color"));
		if (val != 0) {
		    window.toolbox.fillColor = $("#secondColor").css("background-color");
		} else {
		    window.toolbox.fillColor = "rgba(0,0,0,0)";
		}
	});
	//屏蔽右键操作
	$(document).bind("contextmenu",function(e){return false;});
	//屏蔽选中操作
	$(document).bind("selectstart",function(){return false;});
	$("#saveButton").click(function(e) {
		
		var url = document.getElementById("canvas1").toDataURL();
		//alert(url);
		console.log("Save Image:"+url);
		//Canvas2Image.saveAsImage(tmpCanvas.getCanvas(),tmpCanvas.getWidth(),tmpCanvas.getHeight(),"png");
		
	});
	$("#openButton").click(function(e) {
		console.log("Open File");
	});
	$("#textField").blur(function() {
		//alert("complete");
		var x = $(this).css("margin-left");
		var y = $(this).css("margin-top");
		var text = $(this).val();
		//alert(text);
		draw.drawText(text,x,y);
		$(this).hide();
		$(this).val("");
	});
	//draw.drawText("Hi",100,100);
	$("#close").click(function() {
	    console.log("CloseWindow");
	});
	$("#max").click(function() {
	    console.log("MaxWindow");
	});
	$("#min").click(function() {
	    console.log("MinWindow");
	});


});

